package com.atguigu.mapreduce.solution;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

public class SolutionMapper1 extends Mapper<LongWritable, Text, Text, IntWritable> {
    private String filename;
    private final Text key = new Text();
    private final IntWritable value = new IntWritable(1);

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        InputSplit inputSplit = context.getInputSplit();
        if (inputSplit instanceof FileSplit) {
            filename = ((FileSplit) inputSplit).getPath().getName();
        } else {
            filename = "";
        }
    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        String[] words = value.toString().split(" ");
        for (String word : words) {
            this.key.set(word + "," + filename);
            context.write(this.key, this.value);
        }
    }
}
